﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Xml.Serialization;
using AndreySmirnov.BLToolkitUtils.VSPackage.Model;
using AndreySmirnov.BLToolkitUtils.VSPackage.Model.ViewModel;

namespace AndreySmirnov.BLToolkitUtils.VSPackage
{
	public partial class BLTConfigFileEditorControlHost : UserControl
	{
		public BLTConfigFileEditorControlHost()
		{
			InitializeComponent();
		}

		private BLTConfig m_config;
		private UIViewModel m_viewModel;

		public void LoadFile(string fileName)
		{
			Console.Write("Loading file {0}...", fileName);
			var serializer = new XmlSerializer(typeof (BLTConfig));
            try
            {
                using (var s = File.Open(fileName, FileMode.Open, FileAccess.ReadWrite))
                {
                    m_config = (BLTConfig)serializer.Deserialize(s);
                    m_viewModel = new UIViewModel();
                    m_viewModel.Init(m_config);
					m_viewModel.Modified += ViewModel_Modified;
                    bltConfigFileEditorControl1.DataContext = m_viewModel;
                    Console.WriteLine("done.");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error:");
                Console.WriteLine(ex.ToString());
            }
		}

		public event Action Modified;

		public void InvokeModified()
		{
			var handler = Modified;
			if (handler != null)
			{
				handler();
			}
		}

		private void ViewModel_Modified()
		{
			InvokeModified();
		}

		public void SaveFile(string fileName)
		{
			Console.Write("Saving file {0}...", fileName);
			m_viewModel.UpdateData(m_config);
            try
            {
                using (var sw = new StreamWriter(fileName, false, Encoding.UTF8))
                {
                    var serializer = new XmlSerializer(typeof (BLTConfig));
                    serializer.Serialize(sw, m_config);
                    Console.WriteLine("done.");
                }
            }
            catch(Exception ex)
            {
                Console.WriteLine("Error:");
                Console.WriteLine(ex.ToString());
            }
			LoadFile(fileName);
		}
	}
}
